package net.oschina.app.protocol;

import android.util.Log;
import android.widget.Toast;

import net.oschina.app.base.Global;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.simplexml.SimpleXmlConverterFactory;

/**
 * Created by Shinelon on 2017/1/15.
 */

public abstract class AccessProtocol<T> {
    private onAccessNetListener mOnAccessNetListener;
    private T mBody;
    public String mPath;

    public void getData() {
        Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.HOST)
                .addConverterFactory(SimpleXmlConverterFactory.create())
                .build();
        AccessService accessService = retrofit.create(AccessService.class);
        callNet(accessService);
    }

    public Callback<T> callback = new Callback<T>() {
        @Override
        public void onResponse(Call<T> call, Response<T> response) {
            if (response!=null){
                mBody = response.body();
                if (mOnAccessNetListener!=null){
                    mOnAccessNetListener.onSuccess();
                }
            }
        }

        @Override
        public void onFailure(Call<T> call, Throwable t) {
            Toast.makeText(Global.mContext, "网络错误!", Toast.LENGTH_SHORT).show();
            Log.d("heima11",t.getMessage());
            if (mOnAccessNetListener!=null){
                mOnAccessNetListener.onFail();
            }
        }
    };

    //成功访问网络后获取到的数据
    public T getBody() {
        return mBody;
    }

    //调用接口对应的方法获取Call对象
    protected abstract void callNet(AccessService accessService);

    public void setOnAccessNetListener(onAccessNetListener onAccessNetListener) {
        mOnAccessNetListener = onAccessNetListener;
    }

    public interface onAccessNetListener {
        void onSuccess();
        void onFail();
    }

    public void setPath(String path) {
        mPath = path;
    }
}
